import { NodeType } from '@/ts/base/enum';
import { ReportTaskTreeNodeView } from '@/ts/base/model';
import { IReportDistribution } from '@/ts/core/work/assign/distribution/report';
import { Button, DatePicker, Empty, Space, Spin, Tag } from 'antd';
import { Resizable, TreeView } from 'devextreme-react';
import React, { useEffect, useState } from 'react';
import { useEffectOnce } from 'react-use';
import cls from './index.module.less';
import { ProTable } from '@ant-design/pro-components';
import { schema } from '@/ts/base';
import EntityIcon from '@/components/Common/GlobalComps/entityIcon';
import { getAllNodes } from '@/ts/base/common/tree';
import moment from 'moment';

export interface IProps {
  distribution: IReportDistribution;
}

const ClosingPreview: React.FC<IProps> = (props) => {
  const [loaded, setLoaded] = useState(false);
  const [tree, setTree] = useState<ReportTaskTreeNodeView[]>([]);
  const [period, setPeriod] = useState(props.distribution.period);
  const [data, setData] = useState<schema.XPeriod[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [page, setPage] = useState<number>(1);
  const [size, setSize] = useState<number>(10);

  async function loadTree() {
    let tree: ReportTaskTreeNodeView[] = [];

    const space = props.distribution.target.space;
    const roots = await props.distribution.findReportRootNode(space.id);
    if (roots.length == 0) {
      setLoaded(true);
      return;
    }

    const t = await props.distribution.holder.loadTree();
    if (t) {
      [tree] = await t.loadDistributionTree(roots[0], props.distribution);
    }
    setTree(tree);
    setLoaded(true);
    loadData(page, size, period, getAllNodes(tree));
  }

  async function loadData(
    page: number,
    size: number,
    period: string,
    nodes: ReportTaskTreeNodeView[] = [],
  ) {
    if (nodes.length == 0) {
      nodes = getAllNodes(tree);
    }
    const target = props.distribution.task.directory.target;
    const collName = target.space.financial.periodColl.collName;
    const periods = target.resource.genColl<schema.XPeriod>('-' + collName);
    const belongIds = nodes.map((n) => n.belongId);
    const match: { [key: string]: any } = { period };
    if (nodes.length > 0) {
      match['belongId'] = { _in_: belongIds };
    }
    const result = await periods.loadResult({
      requireTotalCount: true,
      options: { match },
      skip: (page - 1) * size,
      take: size,
    });
    if (result.success) {
      const belongMap: { [belongId: string]: schema.XPeriod } = {};
      result.data.forEach((item) => (belongMap[item.belongId] = item));
      const indexing = new Set(belongIds);
      const data: schema.XPeriod[] = [];
      for (const belongId of indexing) {
        const item = belongMap[belongId];
        if (item) {
          data.push({ ...item, remark: '已生成' });
        } else {
          data.push({
            period,
            belongId,
            depreciated: false,
            closed: false,
            remark: '未生成',
          } as schema.XPeriod);
        }
      }
      setData(data);
      setTotal(data.length);
    }
  }

  useEffectOnce(() => {
    loadTree();
  });

  useEffect(() => {
    loadData(page, size, period, getAllNodes(tree));
  }, [page, size, period]);

  if (!loaded) {
    return <Spin>正在加载数据中</Spin>;
  }

  if (tree.length == 0) {
    return <Empty>报表树为空</Empty>;
  }

  return (
    <div className={cls['task']}>
      <div className={cls['content']}>
        <Resizable style={{ width: 400 }}>
          <TreeView
            keyExpr="id"
            dataSource={tree}
            displayExpr="name"
            itemsExpr="children"
            selectionMode="multiple"
            showCheckBoxesMode="selectAll"
            selectNodesRecursive={true}
            onItemSelectionChanged={(e) => {
              loadData(
                page,
                size,
                period,
                e.component.getSelectedNodes().map((item) => item.itemData as any),
              );
            }}
          />
        </Resizable>
        <div style={{ flex: 1 }}>
          <ProTable<schema.XPeriod>
            rowKey="id"
            search={false}
            options={false}
            dataSource={data}
            toolBarRender={() => [
              <DatePicker.MonthPicker
                key="month"
                value={moment(period)}
                onChange={(e) => {
                  if (e) {
                    setPeriod(e.format('YYYY-MM'));
                  }
                }}
              />,
            ]}
            pagination={{
              showSizeChanger: true,
              showTitle: true,
              total: total,
              current: page,
              pageSize: size,
              onChange: (page, size) => {
                setPage(page);
                setSize(size);
              },
            }}
            columns={[
              {
                title: '期间',
                dataIndex: 'period',
                valueType: 'text',
              },
              {
                title: '单位名称',
                dataIndex: 'belongId',
                render: (_, item) => {
                  return <EntityIcon entityId={item.belongId} showName />;
                },
              },
              {
                title: '是否已生成',
                dataIndex: 'belongId',
                render: (_, item) => {
                  return (
                    <Tag color={item.remark == '已生成' ? 'green' : 'red'}>
                      {item.remark}
                    </Tag>
                  );
                },
              },
              {
                title: '是否已折旧',
                dataIndex: 'period',
                render: (_, item) => {
                  return (
                    <Tag color={item.depreciated ? 'green' : 'red'}>
                      {item.depreciated ? '已折旧' : '未折旧'}
                    </Tag>
                  );
                },
              },
              {
                title: '是否已结账',
                dataIndex: 'closed',
                render: (_, item) => {
                  return (
                    <Tag color={item.closed ? 'green' : 'red'}>
                      {item.closed ? '已结账' : '未结账'}
                    </Tag>
                  );
                },
              },
            ]}
          />
        </div>
      </div>
    </div>
  );
};

export default ClosingPreview;
